package org.moon.framework.autoconfigure.sms;

import com.google.common.collect.Maps;
import org.moon.framework.autoconfigure.MoonConstants;
import org.moon.framework.autoconfigure.cache.CacheService;
import org.moon.framework.autoconfigure.config.SpringContextConfig;
import org.moon.framework.autoconfigure.exception.domain.MoonException;
import org.moon.framework.autoconfigure.sms.impl.AliSmsProviderImpl;
import org.moon.framework.autoconfigure.sms.impl.QiniuSmsProviderImpl;
import org.moon.framework.autoconfigure.sms.impl.SmsProvider;
import org.moon.framework.autoconfigure.sms.impl.TencentSmsProviderImpl;
import org.moon.framework.autoconfigure.sms.props.SmsProperties;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * 短信调用入口
 * @author moon
 */
@Configuration
public class SmsTemplate {

    public final static String CACHE_SMS_CONFIG = "sms:config";

    public static Map<String, SmsProvider> smsProviderMap = Maps.newHashMap();

    static {
        smsProviderMap.put(MoonConstants.SmsTypeEnum.aliyun.name(), new AliSmsProviderImpl());
        smsProviderMap.put(MoonConstants.SmsTypeEnum.qiniu.name(), new QiniuSmsProviderImpl());
        smsProviderMap.put(MoonConstants.SmsTypeEnum.tencent.name(), new TencentSmsProviderImpl());
    }

    /**
     * 获取短信发送对象
     */
    public static SmsService getSmsTemplate() {
        CacheService cacheService = SpringContextConfig.getBean(CacheService.class);
        SmsProperties smsProperties = cacheService.get(CACHE_SMS_CONFIG, SmsProperties.class);
        if (smsProperties == null) {
            throw new MoonException(MoonConstants.SMS_CONFIG_NOT_EXISTS);
        }
        return smsProviderMap.get(smsProperties.getName()).builder(smsProperties);
    }
}
